import type { Context } from 'koa';
import { UserService } from '@/services/user';
import { ResponseErrors } from '@/enums/responseErrors';
import { EditProfileDto } from '@/dtos/editProfile.dto';
import { UserRoles } from '@/enums/userEnums';

/**
 * 修改用户信息
*/
export const editProfileController = async (ctx: Context) => {
  const input = ctx.request.body;
  const params = await ctx.vailParams<EditProfileDto>(EditProfileDto, input);

  const { userId = ctx.userId, ...update } = params;

  /**
   * 如果不是管理员，只能需要改自己的profile
  */
  if (ctx.user.role !== UserRoles.admin) {
    if (userId !== ctx.userId) {
      return ctx.sendError(ResponseErrors.userNoPermissionEditProfile);
    }
  }
  
  // 检查用户是否存在
  const isExist = await UserService.checkUserExist(userId);
  if (!isExist) return ctx.sendError(ResponseErrors.userNotExist);
  // 修改用户信息
  const user = await UserService.editUser(userId!, update);
  ctx.sendSuccess(user);
}
